﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
using System.IO;

namespace Ross.OA.Client
{
    public class HttpHelper
    {
        /// <summary>
        /// 发送HTTP GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headers">自定义请求头（可选）</param>
        /// <returns>响应内容</returns>
        public static async Task<string> GetAsync(string url, IDictionary<string, string> headers = null)
        {
            string headstr = string.Empty;
            string apiName = "";
            if (headers != null)
            {
                apiName = headers.FirstOrDefault(k => k.Key == "op").Value;
                headstr = string.Join(";", headers.Select(kvp => $"{kvp.Key}:{kvp.Value}"));
            }
            //Comms.Log($"发送GET请求地址：{url}, 请求头：{headstr}");
            string askContent = $"发送GET请求地址：{url}, 请求头：{headstr}";
            DateTime askTime = DateTime.Now;
            using (HttpClient client = new HttpClient())
            {
                // 添加自定义请求头
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string resp = await response.Content.ReadAsStringAsync();
                //Comms.Log($"GET请求返回：{resp}");
                Comms.DBLog(apiName, askTime, askContent, DateTime.Now, resp);
                return resp;
            }
        }

        /// <summary>
        /// 发送HTTP POST请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">请求数据(JSON格式)</param>
        /// <param name="headers">自定义请求头（可选）</param>
        /// <returns>响应内容</returns>
        public static async Task<string> PostAsync(string url, string data, IDictionary<string, string> headers = null)
        {
            string headstr = string.Empty;
            string apiName = "";
            if (headers != null)
            {
                apiName = headers.FirstOrDefault(k => k.Key == "op").Value;
                headstr = string.Join(";", headers.Select(kvp => $"{kvp.Key}:{kvp.Value}"));
            }
            string askContent = $"发送POST请求地址：{url}, 请求头：{headstr}, 参数：{data}";
            DateTime askTime = DateTime.Now;
            //Comms.Log($"发送POST请求地址：{url}, 请求头：{headstr}, 参数：{data}");
            using (HttpClient client = new HttpClient())
            {
                // 添加自定义请求头
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }
                var buffer = System.Text.Encoding.UTF8.GetBytes(data);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                //StringContent 传递JSON，接口方无法识别
                //StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
                //content.Headers.ContentLength = Encoding.UTF8.GetByteCount(data);

                HttpResponseMessage response = await client.PostAsync(url, byteContent);
                response.EnsureSuccessStatusCode();
                string resp = await response.Content.ReadAsStringAsync();
                //Comms.Log($"POST请求返回：{resp}");
                Comms.DBLog(apiName, askTime, askContent, DateTime.Now, resp);
                return resp;
            }
        }
        
    }
}
